
import logging

log = logging.getLogger('memebase.utils')
log.setLevel(logging.DEBUG)

def access_denied_response(message="You don't have authorization to perform this action",
        template='access_denied.html'):
    from django.shortcuts import render_to_response
    return render_to_response(template, {'message': message})


def requires_logged_user(google_admin=False, test=None):
    def _requires_logged_user(view):
        # requires python 2.5 or greater
        from functools import wraps
        @wraps(view)
        def view_call(request, *args, **kw):
            from google.appengine.api import users
            user = users.get_current_user()
            if not user:
                from django.http import HttpResponseRedirect           
                return HttpResponseRedirect(users.create_login_url(request.META['PATH_INFO']))
            elif google_admin and not users.is_current_user_admin():
                message = 'You need to be the administrator of this site to perform this action'
                return access_denied_response(message)
            elif test and not test(user, *args, **kw):
                return access_denied_response()    
            else:
                return view(request, *args, **kw)
        return view_call
    return _requires_logged_user
     
